package com.study.controller;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.study.entity.common.CommonRequestEntity;
import com.study.entity.common.CommonResponseEntity;
import com.study.entity.db3.Account;
import com.study.enumeration.ResponseEnum;
import com.study.exception.DefinitionException;
import com.study.service.db3.IAccountService;
import com.study.util.ResponseUtil;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.MD5;

/**
 * 账户 前端控制器
 * 
 * @author chenk
 *
 */
@Controller
@RequestMapping("/account")
public class AccountController {

	/**
	 * 日志
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(CustomerController.class);

	@Autowired
	private IAccountService accountService;

	/**
	 * 进入列表页
	 * 
	 * @return
	 */
	@GetMapping("/toList")
	public String toList() {
		return "/account/accountList";
	}

	/**
	 * 查询列表
	 * 
	 * @param requestEntity
	 * @return
	 */
	@GetMapping("/list")
	@ResponseBody
	public CommonResponseEntity<Map<String, Object>> list(CommonRequestEntity requestEntity) {
		PageHelper.startPage(requestEntity.getPage(), requestEntity.getLimit());
		Page<Account> accounts = accountService.queryAccounts(requestEntity.getRequestParams());
		return ResponseUtil.buildPage(accounts);
	}

	/**
	 * 进入新增页面
	 * 
	 * @return
	 */
	@GetMapping("/toAdd")
	public String toAdd(Model model) {
		// List<Role> roles = roleService.queryRoles();
		// model.addAttribute("roles", roles);
		return "/account/accountAdd";
	}

	/**
	 * 新增用户
	 * 
	 * @param account
	 * @return
	 */
	@PostMapping
	@ResponseBody
	public CommonResponseEntity<Object> add(@RequestBody Account account) {
		try {
			String userName = account.getUsername();
			if (!StringUtils.hasLength(userName)) {
				return ResponseUtil.error(ResponseEnum.NOT_PARAM_USER_OR_ERROR_ACCOUNTID);
			}
			Integer count = accountService.countAccounts(account.getUsername(), account.getAccountId());
			if (count > 0) {
				return ResponseUtil.error(ResponseEnum.EXIST_USER);
			}
			this.setPasswordAndSalt(account);
			accountService.saveAccount(account);
			return ResponseUtil.success();
		} catch (Exception e) {
			LOGGER.error("保存失败：" + e.getMessage());
			throw new DefinitionException(ResponseEnum.OPR_FAIL);
		}
	}

	/**
	 * 设置密码
	 * 
	 * @param account
	 */
	private void setPasswordAndSalt(Account account) {
		String password = account.getPassword();
		String salt = UUID.fastUUID().toString().replaceAll("-", "");
		MD5 md5 = new MD5(salt.getBytes());
		String digestHex = md5.digestHex(password); // 加密后的密文密码
		account.setPassword(digestHex);
		account.setSalt(salt);
	}

	/**
	 * 重名校验
	 * 
	 * @param username
	 * @param accountId
	 * @return
	 */
	@GetMapping({ "/{username}", "/{username}/{accountId}" })
	@ResponseBody
	public CommonResponseEntity<Object> checkUsername(@PathVariable String username,
			@PathVariable(required = false) Long accountId) {
		Integer count = accountService.countAccounts(username, accountId);

		return ResponseUtil.success(count);
	}

	/**
	 * 进入详情页
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("toDetail/{id}")
	public String toDetail(@PathVariable Long id, Model model) {
		Account account = accountService.getAccountById(id);
		model.addAttribute("account", account);
		return "account/accountDetail";
	}

	/**
	 * 进入更新页面
	 * 
	 * @return
	 */
	@GetMapping("toUpdate/{id}")
	public String toUpdate(@PathVariable Long id, Model model) {
		Account account = accountService.getAccountById(id);
		model.addAttribute("account", account);

		// List<Role> roles = roleService.queryRoles();
		// model.addAttribute("roles", roles);
		return "account/accountUpdate";
	}

	/**
	 * 修改账户
	 * 
	 * @param account
	 * @return
	 */
	@PutMapping
	@ResponseBody
	public CommonResponseEntity<Object> updateSubmit(@RequestBody Account account) {
		try {
			Long accountId = account.getAccountId();
			String username = account.getUsername();
			if (!StringUtils.hasLength(username) || accountId == null) {
				return ResponseUtil.error(ResponseEnum.NOT_PARAM_USER_OR_ERROR_ACCOUNTID);
			}
			Integer count = accountService.countAccounts(account.getUsername(), account.getAccountId());
			if (count > 0) {
				return ResponseUtil.error(ResponseEnum.EXIST_USER);
			}
			if (StringUtils.hasLength(account.getPassword())) {
				setPasswordAndSalt(account);
			} else {
				account.setPassword(null);
			}
			accountService.updateAccount(account);
			return ResponseUtil.success();
		} catch (Exception e) {
			LOGGER.error("修改失败：" + e.getMessage());
			throw new DefinitionException(ResponseEnum.OPR_FAIL);
		}
	}

	/**
	 * 删除账户
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@DeleteMapping("/{id}")
	@ResponseBody
	public CommonResponseEntity<Object> delete(@PathVariable Long id, HttpSession session) {
		try {
			Account account = (Account) session.getAttribute("account");
			if (account.getAccountId().equals(id)) {
				return ResponseUtil.error(ResponseEnum.NOT_DELETE_MYSELF);
			}
			accountService.deleteById(id);
			return ResponseUtil.success();
		} catch (Exception e) {
			LOGGER.error("删除失败：" + e.getMessage());
			throw new DefinitionException(ResponseEnum.OPR_FAIL);
		}
	}

}
